package com.dgt.trade.controller;

import com.dgt.trade.entitys.trade.Data;
import com.dgt.trade.entitys.User;
import com.dgt.trade.entitys.trade.Product;
import com.dgt.trade.entitys.yifu.Subaccounts_select;
import com.dgt.trade.entitys.yifu.Subtransfers;
import com.dgt.trade.entitys.yifu.YF_Currency;
import com.dgt.trade.service.RemindService;
import com.dgt.trade.service.RuleService;
import com.dgt.trade.service.TradeService;
import com.dgt.trade.utils.*;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.*;


@Controller
@RequestMapping(value = "/trade")
public class TradeController extends BaseController {

    @Autowired
    TradeService tradeService;

    @Autowired
    RuleService ruleService;

    @Autowired
    RemindService remindService;

    String bool = "";

    @RequestMapping(value = "/index")
    public ModelAndView index(Integer isDomestic, String market) {
        ModelAndView view = new ModelAndView();
        if (isDomestic == null) {
            isDomestic = 0;
            view.getModel().put("domestic", "");
        }
        //国内，国外样式
        if (isDomestic == 0) {
            view.getModel().put("domestic", "bgcolor_red");
        } else {
            view.getModel().put("notdomestic", "bgcolor_red");
        }
        List<Product> products = tradeService.getProducts();
        view.getModel().put("products", products);
        view.setViewName("trade/index");
        return view;
    }

    @RequestMapping(value = "/getIndexData")
    public @ResponseBody
    List<Product> getIndexData(Integer isDomestic, String market) {
        if (isDomestic == null) {
            isDomestic = 0;
        }
        getProdect();
        return tradeService.getProducts();
    }

    public void getProdect() {
        Product product = new Product();
        Data data = new Data();
        wsGetHTML ws = new wsGetHTML();
        String str = ws.getHTMLproduct();
        JSONArray jsonArray = new JSONArray(str);
        for (int i = 0; i < jsonArray.length(); i++) {
            product.setLastPrice(BigDecimal.valueOf(Double.valueOf(jsonArray.getJSONObject(i).get("NewPrice").toString())));
            product.setChangeCount(BigDecimal.valueOf(Double.valueOf(jsonArray.getJSONObject(i).get("PriceChangeRatio").toString())));
            product.setCode((String) jsonArray.getJSONObject(i).get("Symbol"));
            tradeService.updatePriceByCode(product.getCode(), product.getLastPrice().toString(), product.getChangeCount().toString());

            data.setAmount(jsonArray.getJSONObject(i).get("Amount").toString());
            data.setVolume(jsonArray.getJSONObject(i).get("Volume").toString());
            data.setChangeCount(jsonArray.getJSONObject(i).get("PriceChangeRatio").toString());
            data.setHigh(jsonArray.getJSONObject(i).get("High").toString());
            data.setLow(jsonArray.getJSONObject(i).get("Low").toString());
            data.setOpen(jsonArray.getJSONObject(i).get("Open").toString());
            data.setClose(jsonArray.getJSONObject(i).get("LastClose").toString());
            data.setLastPrice(jsonArray.getJSONObject(i).get("NewPrice").toString());
            data.setCode(jsonArray.getJSONObject(i).get("Symbol").toString());
            data.setBv(jsonArray.getJSONObject(i).get("BV1").toString());
            data.setSv(jsonArray.getJSONObject(i).get("SV1").toString());
            data.setBp(jsonArray.getJSONObject(i).get("BP1").toString());
            data.setSp(jsonArray.getJSONObject(i).get("SP1").toString());
            tradeService.updateDataByCode(data.getCode(), data.getLastPrice(), data.getHigh(), data.getLow(), data.getOpen(), data.getClose(), data.getVolume(), data.getAmount(), data.getBv(), data.getSv(), data.getBp(), data.getSp(), data.getChangeCount());
        }
    }

    @RequestMapping(value = "/product")
    public ModelAndView product(String code, Model m) {
        ModelAndView view = new ModelAndView();
        User user = getUser(request);
        HashMap<String, Object> pro_data = tradeService.getFreshData(code);
        HashMap<String, Object> rule = ruleService.getRuleByCode(code);
        String message = DateUtil.isBelong(Integer.parseInt(rule.get("is_domestic").toString()), rule.get("code").toString(), rule.get("start_time").toString(), rule.get("end_time").toString());
        if (pro_data != null && rule != null && message != null && code != null) {
            view.getModel().put("code", code);
            view.getModel().put("message", message);
            view.getModel().put("rule", rule);
            view.getModel().put("pro_data", pro_data);
            m.addAttribute("user", user);
            view.setViewName("trade/ceshi");
            /*view.setViewName("trade/product_detail");*/
        } else {
            view.setViewName("error/404");
        }
        return view;
    }

    @RequestMapping(value = "/getKdata")
    public @ResponseBody
    HashMap<String, Object> getKdata(String code, Integer type) {

//		if(type>0){
        return tradeService.getKByCodeAndType(code, type);
//		}else {
//			return  tradeService.getFsData(code);
//		}

    }

    @RequestMapping(value = "/getFreshData")
    public @ResponseBody
    HashMap<String, Object> getFreshData(String code) {

        return tradeService.getFreshData(code);
    }

    @RequestMapping(value = "/monijiaoyi")
    public ModelAndView monijiaoyi() {
        ModelAndView view = new ModelAndView();
        view.setViewName("trade/monijiaoyi");
        return view;
    }

    @RequestMapping(value = "/order_list")
    public ModelAndView order_list(Model model) {

        User user = getUser(request);
        ModelAndView view = new ModelAndView();
        if (user != null) {
            model.addAttribute("user", user);
            view.setViewName("trade/order_list");
        } else {
            view.setViewName("login");
        }
        return view;
    }

    @RequestMapping(value = "/jiesuan")
    public ModelAndView jiesuan() {
        ModelAndView view = new ModelAndView();
        view.setViewName("trade/jiesuan");
        return view;
    }

    @RequestMapping(value = "/mock_trade")
    public ModelAndView mock_trade() {
        ModelAndView view = new ModelAndView();
        List<Product> productList = tradeService.getProducts();
        if (productList != null) {
            view.getModel().put("products", productList);
            view.setViewName("trade/mock_trade");
        } else {
            view.setViewName("error/404");
        }
        return view;
    }

    @RequestMapping(value = "/edit_market")
    public ModelAndView edit_market() {
        ModelAndView view = new ModelAndView();
        List<Product> productList = tradeService.getProducts();
        if (productList != null) {
            view.getModel().put("products", productList);
            view.setViewName("trade/edit_market");
        } else {
            view.setViewName("error/404");
        }
        return view;
    }

    @RequestMapping(value = "/moni_market")
    public ModelAndView moni_market() {
        ModelAndView view = new ModelAndView();
        List<Product> productList = tradeService.getProducts();
        if (productList != null) {
            view.getModel().put("products", productList);
            view.setViewName("trade/moni_market");
        } else {
            view.setViewName("error/404");
        }
        return view;
    }

    @RequestMapping(value = "/systerm_notice")
    public ModelAndView systemNotice() {
        ModelAndView view = new ModelAndView();
        view.setViewName("trade/systerm_notice");
        return view;
    }

    @RequestMapping(value = "/hangqing_notice")
    public ModelAndView hangqing_Notice(String code) {
        ModelAndView view = new ModelAndView();
        HashMap<String, Object> hashMap = tradeService.getFreshData(code);
        if (hashMap != null) {
            view.getModel().put("pro_data", hashMap);
            /*remindService.insertRemind();*/
            view.setViewName("trade/hangqingnotice");
        } else {
            view.setViewName("error/404");
        }
        return view;
    }

    @RequestMapping(value = "/infor_index")
    public ModelAndView infor_Index() {
        ModelAndView view = new ModelAndView();
        view.setViewName("infor_index");
        return view;
    }

    @RequestMapping(value = "/zxyw")
    public ModelAndView ZiXunYinWen() {
        ModelAndView view = new ModelAndView();
        view.setViewName("trade/zxyw");
        return view;
    }

    @RequestMapping(value = "/topay")
    public void ToPay(String money, String name, String ip, String SubAccountID) throws IOException {
        String time = String.valueOf(new Date().getTime());
        com.dgt.trade.utils.Data data = new com.dgt.trade.utils.Data();
        Integer status = null;
        String message = null;
        String ArrivalAmount = null;
        String AvailableFund = null;
        String MarginFund = null;
        String BaseCurrency = null;
        String ExecRate = null;
        User user = getUser(request);
        HttpSession session = request.getSession();
        session.setAttribute("ip", ip);
        session.setAttribute("user", user);
        session.setAttribute("money", money);
        session.setAttribute("body", name);
        session.setAttribute("SubAccountID", SubAccountID);

        //逸富入金
        Map<String, String> map = new LinkedHashMap<String, String>();
        Subtransfers subtransfers = new Subtransfers();
        subtransfers.setSubAccountID(SubAccountID);
        subtransfers.setCurrency(YF_Currency.CURRENCY_CNY);
        subtransfers.setDirection("0");
        subtransfers.setAmount(BigDecimal.valueOf(Double.valueOf(money)));
        if (subtransfers.getDirection().equals("1")) {
            //todo 当Direction为1时是否判断占用保证金大于0，如果大于0则不能出金
        }
        subtransfers.setPosition(true);
        subtransfers.setTimeStamp(time);
        subtransfers.setVersion("1.0");
        String str = MD5Util.MD5_rujin(subtransfers.getSubAccountID(), subtransfers.getCurrency(), subtransfers.getDirection(), String.valueOf(subtransfers.getAmount()), String.valueOf(subtransfers.isPosition()), subtransfers.getTimeStamp(), subtransfers.getVersion());
        subtransfers.setSignMsg(str);

        map.put("SubAccountID", subtransfers.getSubAccountID());
        map.put("Currency", subtransfers.getCurrency());
        map.put("Direction", subtransfers.getDirection());
        map.put("Amount", subtransfers.getAmount().toString());
        map.put("Position", String.valueOf(subtransfers.isPosition()));
        map.put("TimeStamp", subtransfers.getTimeStamp());
        map.put("Version", subtransfers.getVersion());
        map.put("SignMsg", subtransfers.getSignMsg());

        String query = MapToStringSplicing.createLinkStringByGet(map);

        String result = HttpClientUtil.putProcessRuntimeTask("http://120.55.162.84:8050/api/subtransfers?" + query, map);
        JsonParser parser = new JsonParser();
        JsonObject object = (JsonObject) parser.parse(result);
        JsonArray array = null;
        JsonObject subObject = null;
        status = object.get("status").getAsInt();
        if (status == 0 || status == 2003 || status == 2004) {
            array = object.get("data").getAsJsonArray();
            for (int i = 0; i < array.size(); i++) {
                subObject = array.get(i).getAsJsonObject();
                ArrivalAmount = subObject.get("ArrivalAmount").getAsString();
                AvailableFund = subObject.get("AvailableFund").getAsString();
                MarginFund = subObject.get("MarginFund").getAsString();
                BaseCurrency = subObject.get("BaseCurrency").getAsString();
                ExecRate = subObject.get("ExecRate").getAsString();
            }
        } else {
            message = object.get("message").getAsString();
        }
        if (status == 0) {
            response.sendRedirect("/payjftjd.do");
        } else {
            data.setCode(status);
            data.setMsg(message);
            response.sendRedirect("/error/404");
        }
    }
}